using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using QFramework;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;

public class UIGameMain : MonoBehaviour,IController
{
    public Transform PropItemRoot;
    public GameObject PropItemPrefab;
    public List<PropDataData> PropDatas;
    public Dictionary<PropData,int> numDic;
    public Dictionary<PropData,PropItem> propItemDic;
    public CanvasGroup CanvasGroup;

    public IArchitecture GetArchitecture() => GameArchitecture.Interface;

    private void Awake() 
    {
        propItemDic = new Dictionary<PropData, PropItem>();
        numDic = new Dictionary<PropData, int>();
        PropDatas = this.GetModel<StageModel>().m_StageData.propDatas;
        foreach(var item in PropDatas)
        {
            numDic.Add(item.propData,item.number);
        }
    }

    private void Start() 
    {
        this.RegisterEvent<GameStart>(OnGameStart).UnRegisterWhenGameObjectDestroyed(gameObject);
        this.RegisterEvent<PropSet>(OnPropSet).UnRegisterWhenGameObjectDestroyed(gameObject);
        this.RegisterEvent<PropReset>(OnPropReset).UnRegisterWhenGameObjectDestroyed(gameObject);
        foreach (var item in PropDatas)
        {
            var propItem = GameObject.Instantiate(PropItemPrefab,PropItemRoot).GetComponent<PropItem>();
            propItem.SetData(item);
            propItemDic.Add(item.propData,propItem);
        }
    }
    private void OnGameStart(GameStart gameStart)
    {
        DOTween.To(()=> CanvasGroup.alpha,x => CanvasGroup.alpha = x,0,1);
    }
    void OnPropSet(PropSet propSet)
    {
        if(numDic.ContainsKey(propSet.propData))
        {
            numDic[propSet.propData]--;
            if(numDic[propSet.propData]<0) numDic[propSet.propData] = 0;
            propItemDic[propSet.propData].ChangeNum(numDic[propSet.propData]);
        }
    }
    void OnPropReset(PropReset propReset)
    {
        foreach (var item in propItemDic)
        {
            item.Value.ReSet();
        }
        foreach(var item in PropDatas)
        {
            numDic[item.propData] = item.number;
        }
    }
}
